<?php
namespace App\Common;

use App\Model\MemberToken as MemberTokenModel;
use Platform\Model\Member as MemberModel;
use PhalApi\Exception\BadRequestException;

/**
 * 管理员会话服务
 * @author zh
 */
class Admin {

    public function __construct() {

    }

    /**
     * 退出登录，清除会话
     */
    public function logout() {
        $tokenModel = new MemberTokenModel();
        //根据当前token值设置过期时间为退出时间
        $sign = $_SERVER['HTTP_AUTHORIZATION'];
        if( empty( $sign ) ){
            throw new BadRequestException('token验证失败！', 8);
        }
        $sign = explode(' ',$sign);
        $res = $tokenModel->updateAll(array('token'=>$sign[1]),array('invalid_time'=>time()-1));
        if( empty( $res ) ){
            throw new BadRequestException('退出失败！', 8);
        }
    }

    /**
     * 检测是否登录
     */
    public function check($isStopIfNoLogin = TRUE) {
        $whitelist=\PhalApi\DI()->config->get('app.whitelist');
        if($_GET['service'] == null){
            if( in_array($_GET['s'],$whitelist) ){
                return array();
            }
        }else{
            if( in_array($_GET['service'],$whitelist) ){
                return array();
            }
        }
        //增加header头验证
        $tokenModel = new MemberTokenModel();
        $MemberModel = new MemberModel();
        //获取header里的参数Authorization
        //如果header里放入的值为Authorization，到header里会自动加上HTTP_，并且转化为大写，取值时如下
        $sign = $_SERVER['HTTP_AUTHORIZATION'];
        if( empty( $sign ) ){
            throw new BadRequestException('token验证失败！', 8);
        }
        $sign = explode(' ',$sign);
        $tokenData = $tokenModel->getData(array('token'=>$sign[1]));
        if (!empty($tokenData)&&$tokenData['invalid_time']>time()) {
            //根据user_id查询用户的基本信息
            $userData = $MemberModel->get($tokenData['user_id'],"id as user_id,member_mobile,member_name,member_avatar,region,address,member_birthday,member_sex,password,from_unixtime(add_time, '%Y-%m-%d %H:%i:%S') as add_time");
            //根据role_id查询角色名称
            return $userData;
        }
        if ($isStopIfNoLogin) {
            throw new BadRequestException('请登录~', 8);
        }
        return FALSE;
    }
}